import axios from "axios"

import { ElLoading, ElMessage } from "element-plus"
import router from "@/router"

import Message from "../utils/Message"

import VueCookies from 'vue-cookies'

//表单提交的 content-type
const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8'
// JSON 提交的 content-type
const contentTypeJson = 'application/json'
// 默认响应数据类型
const responseTypeJson = 'json'

let loading = null

// 创建 axios 实例
const instance = axios.create({
    baseURL: '/api', // 基础 URL
    timeout: 10 * 2000, // 请求超时时间
})

// 请求拦截器
instance.interceptors.request.use(
    (config) => {
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: '加载中...',
                background: 'rgba(0, 0, 0, 0.7)',
            })
        }
        return config;
    },
    (error) => {
        if (config.showLoading && loading) {
            loading.close();
        }
        Message.error('请求发送失败');
        return Promise.reject('请求发送失败');
    }
);

// 响应拦截器
instance.interceptors.response.use(
    (response) => {
        const { showLoading, errorCallback, showError = true, responseType } = response.config;

        // 获取请求地址
        const requestUrl = response.config.url

        if (showLoading && loading) {
            loading.close();
        }
        // 获取接口返回的数据
        const responseDate = response.data;
        // 如果响应是文件类型，直接返回原始数据，不做处理
        if (responseType == 'arraybuffer' || responseType == 'blob') {
            return responseDate;
        }
        // 根据接口返回的状态码进行处理
        if (responseDate.code === 200) {
            // 如果登录时间还有半个小时到期 则进行续费
            const now = Date.now(); // 当前时间
            const halfHour = 30 * 60 * 1000; // 半小时的毫秒数
            let userInfo = VueCookies.get('userInfo');

            if (userInfo != null && userInfo.expireTime - now <= halfHour) {
                // 判断是否是登录或注册接口
                if (!urequestUrlrl.includes('/login') || !requestUrl.includes('/register')) {

                    const token = VueCookies.get('token')
                    const expireTime = new Date(now.getTime() + 1 * 24 * 60 * 60 * 1000); // 1天 = 24*60*60*1000 毫秒
                    result.data.expireTime = expireTime.getTime()
                    // 讲用户的登录信息存储到cookie
                    proxy.VueCookies.set('userInfo', userInfo, '1d');
                    proxy.VueCookies.set('token', token, '1d');
                }
            }
            return responseDate;
        } else if (responseDate.code === 455) {
            router.push('/login?redirectUrl=' + encodeURI(router.currentRoute.value.path));
            return Promise.reject({ showError: true, message: '登录超时' });
        } else if (responseDate.code === 40101) {
            debugger
            router.push('/login?redirectUrl=' + encodeURI(router.currentRoute.value.path));
            return Promise.reject({ showError: true, message: '账号已在其他设备登录' });
        }
        else {
            if (errorCallback) {
                errorCallback(responseDate.msg)
            }
            return Promise.reject({ showError, message: responseDate.msg });
        }
    },
    // 响应失败统一处理
    (error) => {
        if (error.config.showLoading && loading) {
            loading.close();
        }
        return Promise.reject({ showError: true, message: '网络异常' });
    }
);

// 封装请求方法
const request = (config) => {
    const { url, params, dataType, showLoading = true, responseType = responseTypeJson } = config;

    let contentType = contentTypeForm;
    let formData = new FormData();
    for (let key in params) {
        formData.append(key, params[key] == undefined ? '' : params[key]);
    }

    if (dataType != null && dataType === 'json') {
        contentType = contentTypeJson;
    }

    let userInfo = VueCookies.get('userInfo') == null ? null : VueCookies.get('userInfo');

    let headers = {
        'Content-Type': contentType,
        'X-Requested-With': 'XMLHttpRequest',
        'AccessToken': userInfo == null ? null : userInfo.email,
    }

    return instance.post(url, formData, {
        onUploadProgress: (event) => {
            if (config.uploadProgredssCallback) {
                config.uploadProgredssCallback(event);
            }
        },
        responseType: responseType,
        headers: headers,
        showLoading: showLoading,
        errorCallback: config.errorCallback,
        showError: config.showError,
        responseType: responseType,
    }).catch((error) => {
        console.log("请求成功",error);
        if (error.showError) {
            Message.error(error.message || '请求失败');
        }
        return null
    });
}

export default request;